<?php

namespace app\job;

use app\commons\model\Member;
use app\commons\model\Sale;
use think\Exception;
use think\queue\Job;
use think\Db;
use video\Alivideo;
use app\commons\model\ActivityVideo;
use douyin\Dy;
use app\commons\model\MemberVideo;

/**
 * 队列发布抖音视频
 */
class DouyinVideo
{
    /**
     * 执行队列
     * @param Job $job
     * @param $data
     */
    public function fire(Job $job, $data){
        $info = $this->isDone($data);
        if(!$info){
            //数据不存在或者已执行完成，删除队列
            $job->delete();
            echo '删除队列成功！数据ID：'.$data['activity_video_id'].PHP_EOL;
        }else{
            //执行队列方法，下载文件
            echo '开始处理发布视频！数据ID：'.$data['activity_video_id'].PHP_EOL;
            Db::startTrans();
            try {
                $video = ActivityVideo::where(['id'=>$data['activity_video_id']])->find();
                $user = Member::where(['id'=>$data['user_id']])->find();
                $sale = Sale::where(['id'=>$data['sale_id']])->find();
                $videoRes = Dy::releaseVideo($user['openid'],$user['access_token'],$sale,$video['path']);
                $item_id = $videoRes['data']['item_id'];//获取视频ID
                //增加用户发布的视频
                $createData = [
                    'member_id'=>$user['id'],
                    'sale_id'=>$data['sale_id'],
                    'item_id'=>$item_id,
                ];
                $res = MemberVideo::create($createData);
                if(!$res){
                    throw new Exception('视频发布失败，5秒后重试！');
                }
                //更新视频数据
                $res = ActivityVideo::where(['id'=>$data['activity_video_id']])->update(['is_complete'=>1]);
                if(!$res) throw new Exception('视频发布失败，5秒后重试啦！');
                echo '视频发布成功'.PHP_EOL;
                Db::commit();
                $job->delete();
            }catch (Exception $exception){
                Db::rollback();
                echo '数据异常：'.$exception->getMessage().PHP_EOL;
                $job->release(5);
            }
        }
    }

    /**
     * 验证当前数据是否执行完
     * @param $data
     */
    private function isDone($data){
        $info = ActivityVideo::where(['id'=>$data['activity_video_id']])->find();
        if(!$info){
            return false;
        }
        if($info['is_complete'] == 1){
            return false;
        }
        return true;
    }
}